﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace DZDPSpider
{
    public class ExcelHelper : IDisposable
    {
        private string fileName = null; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExcelHelper(string fileName)
        {
            this.fileName = fileName;
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();
            disposed = false;
        }

        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            
            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);

                    // 设置单元格的宽度
                    sheet.SetColumnWidth(0, 50 * 256);
                    sheet.SetColumnWidth(1, 20 * 256);
                    sheet.SetColumnWidth(2, 20 * 256);
                    sheet.SetColumnWidth(3, 20 * 256);
                    sheet.SetColumnWidth(4, 60 * 256);
                    sheet.SetColumnWidth(5, 30 * 256);
                    sheet.SetColumnWidth(6, 30 * 256);
                    sheet.SetColumnWidth(7, 50 * 256);

                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        ICell cell = row.CreateCell(j);
                        ICellStyle style = workbook.CreateCellStyle();//创建样式对象
                        IFont font = workbook.CreateFont(); //创建一个字体样式对象
                        font.FontName = "宋体"; //和excel里面的字体对应
                        font.FontHeightInPoints = 12;//字体大小
                        font.Boldweight = (short)FontBoldWeight.Bold;//字体加粗
                        style.SetFont(font); //将字体样式赋给样式对象
                        cell.CellStyle = style; //把样式赋给单元格
                        cell.SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        ICell cell = row.CreateCell(j);
                        ICellStyle style = workbook.CreateCellStyle();//创建样式对象
                        IFont font = workbook.CreateFont(); //创建一个字体样式对象
                        font.FontName = "宋体"; //和excel里面的字体对应
                        font.FontHeightInPoints = 12;//字体大小
                        style.SetFont(font); //将字体样式赋给样式对象
                        cell.CellStyle = style; //把样式赋给单元格
                        cell.SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }

    }
}
